package miku.firstgame.net
{
	import flash.utils.ByteArray;

	public class ByteArrayEx extends ByteArray
	{
		public function ByteArrayEx()
		{
			super();
		}

		public function flush():ByteArrayEx
		{
			var newBytes:ByteArrayEx = new ByteArrayEx();

			this.readBytes(newBytes);
			return newBytes;
		}

		public function writeString(value:String):void
		{
			if (value.length == 0)
			{
				writeUnsignedInt(0);
			}
			else
			{
				var currentPosition:int = this.position;
				this.position = currentPosition + 4;
				writeMultiByte(value, "utf-8");
				var newPosition:int = this.position;
				var messageLength:int = newPosition - currentPosition - 4;
				this.position = currentPosition;
				writeUnsignedInt(messageLength);
				this.position = newPosition;
			}
		}

		public function readString():String
		{
			var messageLength:int = readUnsignedInt();
			if (messageLength == 0)
			{
				return "";
			}
			else
			{
				var result:String = readMultiByte(messageLength, "utf-8");
				return result;
			}
		}
	}
}
